package com.zyk.scaffold.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zyk.scaffold.user.entity.Function;
import com.zyk.scaffold.user.mapper.FunctionMapper;
import com.zyk.scaffold.user.service.FunctionService;
import com.zyk.scaffold.user.service.TenantFunctionService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户-功能表 服务实现类
 * </p>
 *
 * @author zhouyk
 * @since 2022-01-24
 */
@Service
public class FunctionServiceImpl extends ServiceImpl<FunctionMapper, Function> implements FunctionService {

    @Autowired
    private TenantFunctionService tenantFunctionService;

    @Override
    public List<Function> getAllFunction() {
        QueryWrapper<Function> functionQueryWrapper = new QueryWrapper<>();
        functionQueryWrapper.lambda().eq(Function::getDeleted, Boolean.FALSE);
        return this.list(functionQueryWrapper);
    }

    @Override
    public boolean refreshFunction(List<Function> adds, List<Function> updates, List<Long> deletedIds, Long userId) {
        if(CollectionUtils.isNotEmpty(deletedIds)){
            UpdateWrapper<Function> functionUpdateWrapper = new UpdateWrapper<>();
            functionUpdateWrapper.lambda().in(Function::getId, deletedIds)
                    .set(Function::getUpdateUser, userId)
                    .set(Function::getDeleted, Boolean.TRUE);
            this.update(functionUpdateWrapper);
        }
        updates.forEach(function -> {
            this.updateById(function);
        });

        List<Long> addIds = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(adds)){
            this.saveBatch(adds);
            addIds = adds.stream().map(Function::getId).collect(Collectors.toList());
        }

        tenantFunctionService.syncSuperTenantFunctionData(addIds, deletedIds);
        return true;
    }
}
